package org.cn.lennon.mybatis.config;

import java.lang.reflect.Method;
import java.util.Set;

import org.cn.lennon.mybatis.annotation.SqlAnnotation;
import org.cn.lennon.mybatis.annotation.SqlMapperAnnotation;
import org.cn.lennon.mybatis.executors.OperationType;
import org.cn.lennon.mybatis.transcation.Transaction;
import org.cn.lennon.mybatis.uitl.ClassScanUtil;

/**
 * 
 * 
 * @author Administrator
 *
 */
public class Configuration {
	
	private Transaction transaction;
	public MapperRegister mapperRegister = MapperRegister.getMapperRegister();

	/**
	 * 扫描类路径下的mapper
	 * 
	 * @param classPath
	 */
	public void builde(String classPath) {
		// 扫描该路径下的所有类
		Set<Class<?>> setClass = ClassScanUtil.getClasses(classPath);
		for (Class<?> clazz : setClass) {

			// 找到被标记位SqlMapper的类
			SqlMapperAnnotation sqlMapperAnnotation = clazz.getAnnotation(SqlMapperAnnotation.class);
			if (sqlMapperAnnotation != null) {
				addMapperStatemnt(clazz);
			}
		}
	}
	
	private void addMapperStatemnt(Class<?> clazz) {
		// 将那些有被标记位sql的方法扫描进来
		Method[] methods = clazz.getMethods();
		for (Method method : methods) {

			// 找到该类下的注解
			SqlAnnotation sqlAnnotation = method.getAnnotation(SqlAnnotation.class);
			if (sqlAnnotation != null) {
				String sql = sqlAnnotation.sql();
				Class<?> resultType = sqlAnnotation.resultType();
				OperationType type = sqlAnnotation.type();
				if (sql != null && sql.length() > 0) {
					String statmentId = clazz.getName() + "." + method.getName();
					MapperStatment mapperStatment = new MapperStatment(statmentId, sql, resultType, type);
					mapperRegister.put(statmentId, mapperStatment);
				}
			}
		}
	}

}
